class MixedStr(object):
    def __init__(self, string):
        self.string = string

    def __len__(self):
        # Calculate the length of a string which may contains Chinese('only supports utf8 encoding')
        try:
            row_l = len(self.string)
            utf8_l = len(self.string.encode('utf-8'))
            return int((utf8_l-row_l)/2+row_l)
        except:
            return 0

    def sub(self, length):
        if length >= self.__len__():
            return self.string

        i = 0
        p = 0

        while True:
                    ch = ord(self.string[i])
                    #1111110x
                    if ch >= 252:
                            p = p + 6
                    #111110xx
                    elif ch >= 248:
                            p = p + 5
                    #11110xxx
                    elif ch >= 240:
                            p = p + 4
                    #1110xxxx
                    elif ch >= 224:
                            p = p + 3
                    #110xxxxx
                    elif ch >= 192:
                            p = p + 2
                    else:
                            p = p + 1

                    if p >= length:
                            break
                    else:
                            i = p

        return self.string[0:i]

